<template>
  <div class="district-container">
    <a-button type="primary" class="add-district-manager" @click="handleAddDistrict">添加片区主管</a-button>
    <a-table :columns="columns" :data-source="districtData" :loading="isLoading" bordered>
      <template
        v-for="col in ['username', 'name', 'address']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e.target.value, record.key, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template slot="operate" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a-button @click="() => save(record.key)" type="primary" class="district-update">确认修改</a-button>
          <!--<a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
            <a>取消</a>
          </a-popconfirm>-->
        </span>
          <span v-else>
          <a-button :disabled="editingKey !== ''" @click="() => edit(record.address, record.key)" type="primary"
                    class="district-update">修改</a-button>
        </span>
          <a-button @click="() => handleDelete(record.id)" type="danger">删除</a-button>
        </div>
      </template>
      <template slot="address" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a-input v-model="selectedAddress || record.address" class="address-container-input" readOnly />
          <a-button class="address-container-button" type="primary" @click="handleChoose(record.address)">选择</a-button>
        </span>
          <span v-else>
            <div>{{record.address}}</div>
        </span>
        </div>
      </template>
      <template slot="deleteDistrict" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-button @click="() => handleDelete(record.id)" type="danger">删除</a-button>
        </div>
      </template>
      <template slot="deploy" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-button @click="() => handleDeploy(record.username)" type="primary" class="deploy-btn">配置</a-button>
        </div>
      </template>
    </a-table>
    <a-modal v-model="visible" title="选择区域" okText="确定" cancelText="取消" @ok="handleChooseOk">
      <div class="address-model-container">
        <a-checkbox-group @change="onChange" :default-value="addressArray">
          <a-row>
            <a-col :span="6"><a-checkbox value="北京市">北京市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="天津市">天津市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="上海市">上海市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="重庆市">重庆市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河北省">河北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山西省">山西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="内蒙古">内蒙古</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="辽宁省">辽宁省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="吉林省">吉林省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="黑龙江省">黑龙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江苏省">江苏省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="浙江省">浙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="安徽省">安徽省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="福建省">福建省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江西省">江西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山东省">山东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河南省">河南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖北省">湖北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖南省">湖南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广东省">广东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广西">广西</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="海南省">海南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="四川省">四川省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="贵州省">贵州省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="云南省">云南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="西藏">西藏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="陕西省">陕西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="甘肃省">甘肃省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="青海省">青海省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="宁夏">宁夏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="新疆">新疆</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="香港">香港</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="澳门">澳门</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="台湾省">台湾省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="研究院">研究院</a-checkbox></a-col>
          </a-row>
        </a-checkbox-group>
      </div>
    </a-modal>

    <a-modal v-model="addDistrictVisible" title="添加片区主管" okText="确定" cancelText="取消"
             @ok="handleAddDistrictOk" @cancel="handleAddDistrictCancel">
      <div class="add-model-container">
        <a-form :form="form">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="片区主管姓名"
          >
            <a-input
              v-decorator="[
          'name',
          { rules: [{ required: true, message: '请输入合法的姓名', pattern: /^[\u4e00-\u9fa5]+$/i }] },
        ]"
              placeholder="请输入片区主管姓名"
            />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="片区主管电话"
          >
            <a-input
              v-decorator="[
          'username',
          { rules: [{ required: true, message: '请输入有效的电话号码', pattern: /^1[3|4|5|7|8][0-9]\d{8}$/ }] },
        ]"
              placeholder="请输入片区主管电话"
            />
          </a-form-item>

          <a-form-item
            :label-col="buttonFormItemLayout.labelCol"
            :wrapper-col="buttonFormItemLayout.wrapperCol"
            label="所属片区"
          >
            <a-input  class="add-district-input" placeholder="所属片区" v-model="dispatchAddress" readOnly />
            <a-button type="primary" class="add-district-button" @click="showDistrictToast">选择</a-button>
          </a-form-item>

        </a-form>
      </div>
    </a-modal>

    <a-modal v-model="addDistrictToastVisible" title="选择区域" okText="确定" cancelText="取消" @ok="handleChooseToastOk">
      <div class="address-model-container">
        <a-checkbox-group @change="onChangeToast">
          <a-row>
            <a-col :span="6"><a-checkbox value="北京市">北京市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="天津市">天津市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="上海市">上海市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="重庆市">重庆市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河北省">河北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山西省">山西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="内蒙古">内蒙古</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="辽宁省">辽宁省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="吉林省">吉林省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="黑龙江省">黑龙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江苏省">江苏省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="浙江省">浙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="安徽省">安徽省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="福建省">福建省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江西省">江西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山东省">山东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河南省">河南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖北省">湖北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖南省">湖南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广东省">广东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广西">广西</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="海南省">海南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="四川省">四川省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="贵州省">贵州省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="云南省">云南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="西藏">西藏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="陕西省">陕西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="甘肃省">甘肃省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="青海省">青海省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="宁夏">宁夏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="新疆">新疆</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="香港">香港</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="澳门">澳门</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="台湾省">台湾省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="研究院">研究院</a-checkbox></a-col>
          </a-row>
        </a-checkbox-group>
      </div>
    </a-modal>

    <a-modal v-model="deployVisible" title="配置客服人员" okText="确定" cancelText="取消" @ok="handleDeployOk">
      <div class="deploy-form-container">
        <a-form :form="dispatchForm">
          <a-row  v-for="(item, index) in serviceList" :key="item.id">
            <a-col  class="single-left-col">
              <a-form-item class="deploy-form-left">
                <div class="deploy-form-single-container">
                  <span class="deploy-form-single-span">客服姓名:</span>
                  <a-input  class="deploy-form-single-input" v-decorator="[`content[${index}].serviceName`,
                  {
                    initialValue: item.serviceName,
                    rules: [{ required: true, message: '请输入合法的姓名', pattern: /^[\u4e00-\u9fa5]+$/i }]
                    },
                ]"
                            placeholder="客服姓名" autoComplete="off" />
                </div>
              </a-form-item>
              <a-form-item class="deploy-form-right">
                <div class="deploy-form-single-container">
                  <span class="deploy-form-single-span">客服电话:</span>
                  <a-input class="deploy-form-single-input" v-decorator="[`content[${index}].serviceUsername`,
                  {
                    initialValue: item.serviceUsername,
                    rules: [{ required: true, message: '请输入有效的手机号码', pattern: /^1[3|4|5|7|8][0-9]\d{8}$/}] },
                ]"
                           placeholder="客服电话" autoComplete="off" />
                </div>
              </a-form-item>
              <a-form-item class="single-left-col-id">
                <div class="deploy-form-single-container">
                  <span class="deploy-form-single-span">客服id:</span>
                  <a-input class="deploy-form-single-input" v-decorator="[`content[${index}].id`,
                  { initialValue: item.id },
                  ]" />
                </div>
              </a-form-item>
              <span class="deploy-delete" @click="deleteContent(item.id)"><a-icon type="close-circle" /></span>
            </a-col>
          </a-row>
        </a-form>
        <div class="deploy-form-add">
          <a-button type="primary" @click="addSingleForm()">添加客服</a-button>
        </div>
      </div>
    </a-modal>

  </div>
</template>

<script>
  const columns = [
    {
      title: '序号',
      dataIndex: 'sequence',
      key: 'sequence',
      width: '8%',
      scopedSlots: { customRender: 'sequence' },
    }, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: '10%',
      scopedSlots: { customRender: 'name' },
    }, {
      title: '账号',
      dataIndex: 'username',
      width: '10%',
      key: 'username',
      scopedSlots: { customRender: 'username' },
    }, {
      title: '区域',
      dataIndex: 'address',
      key: 'address',
      width: '15%',
      scopedSlots: { customRender: 'address' },
    }, {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: '10%',
      scopedSlots: { customRender: 'operate' },
    }, {
      title: '配置',
      dataIndex: 'deploy',
      key: 'deploy',
      width: '10%',
      scopedSlots: { customRender: 'deploy' },
    },
  ];
  const formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  const dispatchFormItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 10 },
  };
  const buttonFormItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  import GLOBAL from '@/api/global_variable'
  import api from '@/server/userConfig';
  export default {
    name: 'DistrictTable',
    components: {
    },
    props: {
      userName: String
    },
    data () {
      return {
        districtData: [],
        columns,
        editingKey: '',
        isLoading: false,
        visible: false,
        addDistrictVisible: false,
        addDistrictToastVisible: false,
        deployVisible: false,
        cacheData: [],
        selectedAddress: '',
        addressArray: [],
        dispatchAddress: '',
        toastSelectedAddress: '',
        formItemLayout,
        buttonFormItemLayout,
        dispatchFormItemLayout,
        serviceList: [],
        managerUsername: '',
        count: 0,
        form: this.$form.createForm(this, { name: 'dynamic_rule' }),
        dispatchForm: this.$form.createForm(this, { name: 'dispatch_form' }),
      }
    },
    mounted () {
      this.getDistrictList();
    },
    methods: {
      // 配置客服的弹框中，点击添加客服;
      addSingleForm () {
        this.count--;
        console.log(this.count);
        // 点击后，dispatchForm;
        this.serviceList.push({
          managerUsername: '',
          serviceName: '',
          serviceUsername: '',
          id: this.count
        });
      },
      // 配置客服的弹框中，点击删除客服;
      deleteContent (id) {
        this.$Modal.confirm({
          title: '确认删除此客服吗?',
          content: '',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            if (id > 0) {
              const res = await api.reqMasterDeleteService({managerServiceId: id});
              console.log(res);
              if (res.MsgCode !== 0) {
                message.info('删除失败');
                return;
              }
            }
            let newServiceList = [];
            // 删除成功后，更新数据;
            const serviceListLength = this.serviceList.length;
            for (let i = 0; i < serviceListLength; i++) {
              if (this.serviceList[i].id !== id) {
                newServiceList.push({
                  id: this.serviceList[i].id,
                  managerUsername: this.serviceList[i].managerUsername,
                  serviceName: this.serviceList[i].serviceName,
                  serviceUsername: this.serviceList[i].serviceUsername,
                })
              }
            }
            this.serviceList = newServiceList;
          },
          onCancel() {}
        })
      },
      // 点击配置
      async handleDeploy (username) {
        this.deployVisible = true;
        this.managerUsername = username;
        // 根据片区主管获取客服人员;
        const res = await api.reqMasterServiceList({username: username});
        //console.log(res);
        if (res.MsgCode !== 0) {
          message.info('获取失败');
        } else {
          const serviceList = res.Data;
          const serviceListLength = serviceList.length;
          for(let i = 0; i < serviceListLength; i++) {
            if(serviceList[i].serviceUsername === username) {
              serviceList.splice(i, 1)
            }
          }
          this.serviceList = serviceList;
        }
      },
      // 点击配置客服弹框的确定按钮;
      handleDeployOk () {
        this.dispatchForm.validateFields(async (err, values) => {
          if (err) { return; }
          //console.log(this.managerUsername, content);
          const content = values.content;
          // 处理数据;
          let contactParamEntities = [];
          let clientData = {};
          //console.log(content);
          const contentLength = content.length;
          for (let i = 0; i < contentLength; i++) {
            if (content[i].id > 0) {
              contactParamEntities.push({
                serviceName: content[i].serviceName,
                serviceUsername: content[i].serviceUsername,
                id: content[i].id,
              })
            } else {
              contactParamEntities.push({
                serviceName: content[i].serviceName,
                serviceUsername: content[i].serviceUsername
              })
            }
          }
          clientData.managerUsername = this.managerUsername;
          clientData.serviceEntities = contactParamEntities;
          const jsonClientData = JSON.stringify(clientData);
          const res = await api.reqMasterAddAndUpdateService(jsonClientData);
          if (res.MsgCode !== 0) {
            this.$message.info('更新失败，请核对后再重试。。。');
          } else {
            this.$message.success('更新成功!');
            this.deployVisible = false;
          }
          this.dispatchForm.resetFields();
        });
      },
      // 点击删除;
      handleDelete (id) {
        this.$Modal.confirm({
          title: '确认删除此片区主管吗?',
          content: '',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            const res = await api.deleteDistrictList({id: id});
            console.log(res);
            if (res.MsgCode === 0) {
              this.$message.success('删除成功');
              // 前端删除此行;
              const dataSource = [...this.districtData];
              this.districtData = dataSource.filter(item => item.id !== id);
            }
          },
          onCancel() {
          }
        })
      },
      // 增加片区主管;
      handleAddDistrict () {
        this.addDistrictVisible = true;
      },
      // 点击添加片区主管的取消;
      handleAddDistrictCancel () {
        this.form.resetFields();
      },
      // 点击添加片区主管的确定;
      handleAddDistrictOk () {
        this.form.validateFields((err, values) => {
          if (!err) {
            //console.log(this.toastSelectedAddress);
            if (this.toastSelectedAddress === "") {
              this.$message.warning('所属片区不能为空');
              return;
            }
            this.addDistrictVisible = false;
            // 发送ajax请求;
            this.handleAddDistrictPerson(this.userName, values, this.toastSelectedAddress);
            this.form.resetFields();
          }
        });
      },
      handleAddDistrictPerson (userName, values, toastSelectedAddress) {
        let areaManagerData = {};
        areaManagerData.username = values.username;
        areaManagerData.name = values.name;
        areaManagerData.phoneNumber = '';
        areaManagerData.adminUsername = userName;
        areaManagerData.address = toastSelectedAddress;
        const jsonData = JSON.stringify(areaManagerData);
        api.addDistrictList(jsonData).then((res) => {
          if (res.MsgCode === 0) {
            this.$message.success('添加成功');
            //window.location.reload();
            this.getDistrictList();
          }
        });
      },
      // 点击增加片区主管的选择按钮;
      showDistrictToast () {
        this.addDistrictToastVisible = true;
      },
      // 点击选择
      handleChoose (address) {
        this.visible = true;
        this.addressArray = address.split(',');
      },
      handleChooseOk () {
        console.log(this.selectedAddress);
        this.visible = false;
      },
      onChange (checkedValues) {
        this.selectedAddress = checkedValues.join(',');
        //console.log('checked = ', checkedValues);
        console.log(this.selectedAddress);
      },
      // 点击添加片区主管的选择的每一项;
      onChangeToast (toastCheckedValues) {
        this.toastSelectedAddress = toastCheckedValues.join(',');
        //console.log(this.toastSelectedAddress);
      },
      handleChooseToastOk () {
        this.dispatchAddress = this.toastSelectedAddress;
        this.addDistrictToastVisible = false;
      },
      async getDistrictList () {
        this.isLoading = true;
        const res =  await api.getDistrictList({username: this.userName});
        this.isLoading = false;
        if (res.MsgCode !== 0) {
          return;
        }
        let districtData = res.Data;
        const districtDataLength = districtData.length;
        for (let i = 0; i < districtDataLength; i++){
          districtData[i].sequence = i + 1;
          districtData[i].key = districtData[i].userInfo.iD;
          districtData[i].username = districtData[i].userInfo.username;
          districtData[i].name = districtData[i].userInfo.name;
          districtData[i].id = districtData[i].userInfo.iD;
          districtData[i].compID = districtData[i].userInfo.compID;
          districtData[i].address = "";
          for (let j = 0; j < districtData[i].managerDistrict.length; j++){
            districtData[i].address += districtData[i].managerDistrict[j].district + ",";
          }
        }
        for (let k = 0; k < districtDataLength; k++){
          if (districtData[k].address !== ""){
            districtData[k].address = districtData[k].address.slice(0,districtData[k].address.length - 1);
          }
        }
        this.districtData = districtData;
        this.cacheData = this.districtData.map(item => ({ ...item }));
      },

      handleChange (value, key, column) {
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          target[column] = value;
          this.districtData = newData;
        }
      },
      edit (address, key) {
        this.addressArray = address.split(',');
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = key;
        if (target) {
          target.editable = true;
          this.districtData = newData;
        }
      },
      save (key) {
        const phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/;
        const nameReg = /^[\u4E00-\u9FA5]{2,6}$/;
        const newData = [...this.districtData];
        const newCacheData = [...this.cacheData];
        const target = newData.filter(item => key === item.key)[0];
        const updateNewData = {};
        updateNewData.adminUsername = this.userName;
        updateNewData.username = target.username;
        updateNewData.name = target.name;
        updateNewData.address = this.selectedAddress || this.addressArray.join(',');
        updateNewData.phoneNumber = '';
        updateNewData.id = target.id;
        if (!nameReg.test(updateNewData.name)) {
          this.$message.error('请输入合法的姓名');
          return;
        } else if (!phoneReg.test(updateNewData.username)) {
          this.$message.error('请输入有效的手机号码');
          return;
        }
        console.log(updateNewData);
        const jsonData = JSON.stringify(updateNewData);
        api.updateDistrictList(jsonData).then((res) => {
          console.log(res);
          if (res.MsgCode === 0) {
            this.$message.success('更新成功');
            setTimeout(() => {
              window.location.reload();
            }, 500);
            //this.getDistrictList();
          }
        });
        const targetCache = newCacheData.filter(item => key === item.key)[0];
        if (target && targetCache) {
          delete target.editable;
          this.districtData = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
        }
        this.editingKey = '';
      },
      cancel (key) {
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = '';
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
          delete target.editable;
          this.districtData = newData;
        }
      },
    }
  }
</script>

<style scoped>
  @import './style.css';
</style>
